import java.util.Random;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierRunable2 {
    // 自定义工作线程
    private static class Worker extends Thread {
        private CyclicBarrier cyclicBarrier;

        public Worker(CyclicBarrier cyclicBarrier) {
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {
            super.run();
            try {
                // 让其他线程进行等待
                doWait();
                cyclicBarrier.await();
                // 执行所有线程
                doWork();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        public void doWork(){
            try {
                System.out.println("--------->>>"+Thread.currentThread().getName() + "开始执行");
                Thread.sleep(Math.abs(new Random().nextInt()%10000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("--------->>>"+Thread.currentThread().getName() + "执行完毕");
        }
        public void doWait(){
            try {
                System.out.println(Thread.currentThread().getName() + "开始等待其他线程");
                Thread.sleep(Math.abs(new Random().nextInt()%10000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        int threadCount = 3;
        CyclicBarrier cyclicBarrier = new CyclicBarrier(threadCount);
        for (int i = 0; i < threadCount; i++) {
            Worker worker = new Worker(cyclicBarrier);
            worker.start();
        }
    }
}